<template>
    <div class="sales-order-container">
        <!-- 页面头部 -->
        <div class="header">
            <h2>销货订单<span v-if="code">编号:{{ code }}</span></h2>
            <div class="header-right">
                <el-button @click="selectSalerOrderList">历史单据</el-button>
                <el-button type="primary" @click="saveAndNew" :disabled="isViewOnly">保存并新增</el-button>
                <el-button @click="save" :disabled="isViewOnly">保存</el-button>
                <el-button @click="openSourceOrderDialog" :disabled="isViewOnly">选择源单</el-button>
                <el-button @click="submit" :disabled="isViewOnly">提交</el-button>
                <el-button @click="audit" :disabled="isViewOnly">审核</el-button>
            </div>
        </div>

        <div style="background-color: white;">
            <div style="background-color: white; padding: 20px; border-radius: 8px; padding-bottom: 0;">
                <!-- 表单区域 -->
                <el-form :model="salesOrderForm" label-width="auto" inline :disabled="isViewOnly">
                    <div class="top-form">
                        <!-- 客户选择 -->
                        <el-form-item label="客户：">
                            <el-input v-model="salesOrderForm.customerName" placeholder="点击选择客户"
                                @click="openCustomerDialog" readonly style="width: 200px;" />
                            <CustomerDialog v-model="customerDialogVisible" @confirm="handleSelectCustomer" />
                        </el-form-item>

                        <!-- 销售员 -->
                        <el-form-item label="销售员：" prop="workName">
                            <el-input v-model="salesOrderForm.workName" placeholder="业务员" style="width: 200px;"
                                readonly />
                        </el-form-item>

                        <!-- 单据日期 -->
                        <el-form-item label="单据日期：" prop="date">
                            <el-date-picker v-model="salesOrderForm.date" type="date" placeholder="选择日期"
                                :disabled="isAudited" />
                        </el-form-item>

                        <!-- 交货日期 -->
                        <el-form-item label="交货日期：" prop="productDate">
                            <el-date-picker v-model="salesOrderForm.productDate" type="date" placeholder="选择日期"
                                :disabled="isAudited" style="width: 200px;" />
                        </el-form-item>

                        <!-- 客户地址 -->
                        <el-form-item label="客户地址：" prop="customerAddress">
                            <el-input v-model="salesOrderForm.customerAddress" placeholder="请输入地址" clearable
                                style="width: 200px;" :disabled="isAudited" />
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <div style="height: 50px;"></div>

            <!-- 商品表格 -->
            <el-table :data="orderDetails" border stripe ref="tableRef" show-summary :summary-method="getSummaries"
                summary-row-class-name="summary-row">
                <!-- 序号列 -->
                <el-table-column label="序号" width="80" align="center">
                    <template #default="scope">
                        <div class="seq-cell" @mouseenter="hoverIndex = scope.$index" @mouseleave="hoverIndex = -1"
                            v-if="!isAudited">
                            <span v-show="hoverIndex !== scope.$index" class="seq-number">
                                {{ scope.$index + 1 }}
                            </span>
                            <div v-show="hoverIndex === scope.$index" class="operation-area">
                                <span class="operation-btn add" @click.stop="addRow(scope.$index)"
                                    title="在下方添加行">+</span>
                                <span class="operation-btn delete" @click.stop="deleteRow(scope.row)" title="删除当前行"
                                    :class="{ disabled: orderDetails.length <= 1 }"
                                    :disabled="orderDetails.length <= 1">−</span>
                            </div>
                        </div>
                        <div v-else class="seq-cell">{{ scope.$index + 1 }}</div>
                    </template>
                </el-table-column>

                <!-- 商品 -->
                <el-table-column label="商品" width="180" align="center">
                    <template #default="scope">
                        <template v-if="scope.row.productInfo">
                            <el-input v-model="scope.row.productInfo.name" style="width: 95%" placeholder="选择商品"
                                @click="openGoodsDialog(scope.row, scope.$index)" readonly />
                        </template>

                    </template>
                </el-table-column>

                <el-table-column label="商品编号" align="center" width="100">
                    <template #default="scope">
                        {{ scope.row.goods_code || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="商品图片" align="center" width="100">
                    <template #default="scope">
                        <el-image v-if="scope.row.productInfo?.imageUrl" :src="scope.row.productInfo.imageUrl"
                            style="width: 50px; height: 50px" fit="cover"
                            :preview-src-list="[scope.row.productInfo.imageUrl]" />
                    </template>
                </el-table-column>

                <el-table-column label="规格" align="center" width="80">
                    <template #default="scope">
                        {{ scope.row.productInfo?.specification || '' }}
                    </template>
                </el-table-column>

                <!-- 采购单位 -->
                <el-table-column label="单位" width="120" align="center">
                    <template #default="scope">
                        <el-select v-if="scope.row.productInfo" v-model="scope.row.productInfo.unitId"
                            style="width: 95%" :disabled="!scope.row.goodsId" @change="updateUnitName(scope.row)">
                            <template v-if="scope.row.productInfo.unitList">
                                <el-option v-for="item in scope.row.productInfo.unitList" :key="item.id"
                                    :label="item.name" :value="item.id" />
                            </template>
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="基本单位" align="center" width="100">
                    <template #default="scope">
                        {{ scope.row.baseUnit?.name || scope.row.productInfo?.unit || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="订购数量" align="center" width="120">
                    <template #default="scope">
                        <div>
                            <el-input v-model.number="scope.row.quantity" type="number" min="1" step="1"
                                style="width: 100%;" @change="handleQuantityChange(scope.row)"
                                :disabled="isAudited || scope.row.gift" />
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="基本数量" align="center" width="100" prop="baseQuantity">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.baseQuantity" disabled style="width: 100%;" />
                    </template>
                </el-table-column>

                <el-table-column label="可用库存" align="center" width="120">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.useCount" type="number" style="width: 100%;" disabled />
                    </template>
                </el-table-column>

                <el-table-column label="品牌" align="center" width="80">
                    <template #default="scope">
                        {{ scope.row.productInfo?.brand || '' }}
                    </template>
                </el-table-column>


                <el-table-column label="仓库" width="120" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.warehouse" readonly placeholder="(所有)"
                            @click="openWarehouseDialog(scope.row)" />
                    </template>
                </el-table-column>



                <!-- 赠品列 -->
                <el-table-column label="赠品" align="center" width="80">
                    <template #default="scope">
                        <el-checkbox v-model="scope.row.gift" :disabled="isAudited"
                            @change="() => handleGiftChange(scope.row)" />
                    </template>
                </el-table-column>



                <el-table-column label="销售单价" align="center" width="120">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.price" type="number" min="0" step="0.01"
                            style="width: 100%;" @change="calculateDetailPrice(scope.row)"
                            :disabled="isAudited || scope.row.gift" />
                    </template>
                </el-table-column>



                <el-table-column label="折扣率(%)" align="center" width="100">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.discount" type="number" min="0" max="100" step="0.01"
                            style="width: 100%;" @change="calculateDetailPrice(scope.row)"
                            :disabled="isAudited || scope.row.gift" />
                    </template>
                </el-table-column>

                <el-table-column label="折扣额" align="center" width="100" prop="discountAmount">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.discountAmount" disabled style="width: 100%;" />
                    </template>
                </el-table-column>

                <el-table-column label="折扣单价" align="center" width="120">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.discountPrice" type="number" step="0.01"
                            style="width: 100%;" disabled />
                    </template>
                </el-table-column>

                <el-table-column label="金额" align="center" width="100" prop="salesCost">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.salesCost" disabled style="width: 100%;" />
                    </template>
                </el-table-column>

                <el-table-column label="税率(%)" align="center" width="100">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.tax" type="number" min="0" max="100" step="0.01"
                            style="width: 100%;" @change="calculateDetailPrice(scope.row)"
                            :disabled="isAudited || scope.row.gift" />
                    </template>
                </el-table-column>

                <el-table-column label="税额" align="center" width="100" prop="taxAmount">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.taxAmount" disabled style="width: 100%;" />
                    </template>
                </el-table-column>


                <el-table-column label="税后单价" align="center" width="120">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.taxPrice" type="number" step="0.01" style="width: 100%;"
                            disabled />
                    </template>
                </el-table-column>



                <el-table-column label="价税合计" align="center" width="120" prop="totalPrice">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.totalPrice" type="number" step="0.01" style="width: 100%;"
                            disabled />
                    </template>
                </el-table-column>

                <el-table-column prop="remarks" label="备注" min-width="150" show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-model="scope.row.remarks" placeholder="请输入备注" :disabled="isAudited"
                            style="width: 100%;" />
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 30px;"></div>
            <!-- 底部表单 -->
            <div style="background: white; padding: 20px; margin-top: 20px;">
                <el-form :model="salesOrderForm" label-width="auto" inline :disabled="isViewOnly">
                    <!-- <el-form-item label="优惠金额" prop="taxCost">
                        <el-input v-model.number="salesOrderForm.taxCost" placeholder="0.00" style="width: 160px;"
                            :disabled="isAudited" @input="calculateTaxEndCost" />
                    </el-form-item>
                    <el-form-item label="优惠后金额" prop="taxEndCost">
                        <el-input v-model.number="salesOrderForm.taxEndCost" placeholder="0.00" style="width: 160px;" />
                    </el-form-item> -->
                    <el-form-item label="交货方式：" prop="delivery">
                        <el-select v-model="salesOrderForm.delivery" placeholder="请选择" style="width: 200px;" clearable
                            :disabled="isAudited">
                            <el-option value="1" label="快递物流" />
                            <el-option value="2" label="自配" />
                            <el-option value="3" label="其他" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="收款条件：" prop="payment" style="padding-left:20px;">
                        <el-select v-model="salesOrderForm.payment" placeholder="请选择" style="width: 200px;" clearable>
                            <el-option value="1" label="现结" />
                            <el-option value="2" label="货到付款" />
                            <el-option value="3" label="分期付款" />
                            <el-option value="4" label="先款后付" />
                            <el-option value="5" label="月结" />
                            <el-option value="6" label="不定期付款" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="备注" prop="remarks" style="padding-top: 20px;">
                        <el-input v-model="salesOrderForm.remarks" type="textarea" :rows="3" placeholder="请输入备注信息"
                            style="width: 1000px;" />

                    </el-form-item>
                </el-form>
            </div>

            <!-- 商品搜索列表弹出对话框 -->
            <FreeGoodsSelect ref="FreeGoodsRef" v-model="showSelectGoods" @confirm="handleSelectedGoods" />


            <!-- 报价单选择弹窗 -->
            <el-dialog v-model="quotationSelectVisible" title="选择源单（报价单）" width="90%" height="70vh" draggable>
                <AddQuotationRecord :selectable="true" :pre-filter-customer-id="salesOrderForm.customerId"
                    @select="handleSelectQuotation" />
            </el-dialog>

            <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="40%" style="height: auto;" draggable
                :show-close="true">
                <!-- 调用仓库的搜索组件 -->
                <WareHouse ref="warehouseRef"
                    :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
                <br /><br />
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="warehouseVisible = false">取消</el-button>
                        <el-button type="primary" @click="warehouseVisible = false">
                            确认
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import CustomerDialog from '@/util/CustomerDialog.vue'
import FreeGoodsSelect from "@/util/FreeGoodsSelect.vue";
import AddQuotationRecord from '@/views/sales/AddQuotationRecord.vue'
import WareHouse from '@/views/basic/WareHouse.vue'

let FreeGoodsRef = ref();
const updateUnitName = (row) => {
    const { productInfo } = row;
    if (!productInfo?.unitList || !productInfo.unitId) {
        productInfo.unitName = null;
        return;
    }
    const selectedUnit = productInfo.unitList.find(u => u.id === productInfo.unitId);
    productInfo.unitName = selectedUnit ? selectedUnit.name : null;
    console.log("当前的unitName:", productInfo.unitName);

    handleUnitChange(row)
};
// 商品搜索对话框展示
const showSelectGoods = ref(false)
function openGoodsDialog(row, index) {
    showSelectGoods.value = true
    currentRow.value = row;
    currentIndex.value = index;
    console.log("当前选中行：", row)
}

const handleUnitChange = (row) => {
    if (!row.productInfo?.unitName || !row.productInfo.unitList) return;

    // 查找选中的单位
    const selectedUnit = row.productInfo.unitList.find(u => u.id == row.productInfo.unitId);
    if (selectedUnit) {
        row.sunitConversion = selectedUnit.conversion || 1;
        row.baseQuantity = Math.round((row.quantity || 0) * row.sunitConversion * 100) / 100;
        console.log(row.baseQuantity)
        validateQuantity(row);
        calculateDetailPrice(row);
    }
}
const handleQuantityChange = (row) => {

    // 查找选中的单位
    const selectedUnit = row.productInfo.unitList.find(u => u.id == row.productInfo.unitId);
    if (selectedUnit) {
        // 正确设置单位转换系数
        row.sunitConversion = selectedUnit.conversion || 1;
        // 更新基础数量
        row.baseQuantity = Math.round((row.quantity || 0) * row.sunitConversion * 100) / 100;
        console.log("基础数量更新为:", row.baseQuantity);
        validateQuantity(row);
        calculateDetailPrice(row);
    }
}
const route = useRoute()
const router = useRouter()

const staffName = sessionStorage.getItem("name") || '';

// 客户对话框启用
const customerDialogVisible = ref(false)
const selectSalerOrderList = () => {
    router.push({
        name: 'salesOrderRecord',
    })
}

const isEditable = computed(() => {
    if (route.query.from === 'edit' && (route.query.status === '1' || route.query.status === '2')) {
        return false
    }
    return true
})
// 是否为查看模式
const isViewOnly = computed(() => !isEditable.value)

// 是否为编辑模式
const isEdit = computed(() => route.query.from === 'edit')
const quotationId = computed(() => route.query.id)

// 商品选择弹窗控制
const goodsVisible = ref(false)

// 当前是否已审核
const isAudited = ref(false)

// 订单编号
const code = ref('')

let currentRow = ref(null), currentIndex = ref(null);
//仓库搜索选中结果
let warehouseVisible = ref(false)
let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
    if (!newVisible) {
        if (warehouseRef.value && warehouseRef.value.selectedArray.length > 0) { //这里需要加上if判断，子组件中没有选择数据时为undefined，可能用于点击仓库，但是没选择，所以导致undefined报错
            currentRow.value.warehouse = warehouseRef.value.selectedArray[0].name //只选择一个，默认第一个
            //   currentRow.value.warehouseCode = warehouseRef.value.selectedArray[0].code //只选择一个，默认第一个
            //获取到仓库编码，存数据库用，仓库name仅用作展示
            //用完之后清空，避免污染其他地方数据
            warehouseRef.value.clearSelected();
             updateStockByWarehouse(currentRow.value); // 调用
        }
    }
})
function openWarehouseDialog(row) {
    warehouseVisible.value = true,
        currentRow.value = row;
}

// 表单数据
const salesOrderForm = reactive({
    id: '',
    customerCode: '',
    customerName: '',
    customerType: '',
    workName: staffName,
    date: new Date(),
    productDate: '',
    customerAddress: '',
    remarks: '',
    payment: '',
    delivery: '',
    taxCost: 0,
    taxEndCost: 0,
    quotationCode: '',
    quotationId: '',
    customerId: ''
})

// 商品表格
const orderDetails = ref([
    {
        id: Date.now(),
        goodsId: '',
        code: '',
        productInfo: {},
        warehouse: '',
        useCount: 0,
        price: 0,
        discount: 0,
        discountPrice: 0,
        tax: 13,
        salesCost: 0,
        discountAmount: 0,
        taxAmount: 0,
        taxPrice: 0,
        quantity: 0,
        totalPrice: 0,
        remarks: '',
        gift: false,
        unitList: [],
        selectedUnit: null,
        baseUnit: null,
        baseQuantity: 0,
        unitConversion: 1
    }
])

// hover 状态
const hoverIndex = ref(-1)

// 表格引用
const tableRef = ref(null)

// 赠品
const handleGiftChange = (row) => {
    if (row.gift) {
        // 原始价格
        row._originalPrice = {
            price: row.price,
            discount: row.discount,
            tax: row.tax,
            quantity: row.quantity || 0
        }
        // 清零
        row.price = 0
        row.discount = 0
        row.tax = 0
        row.discountPrice = 0
        row.salesCost = 0
        row.discountAmount = 0
        row.taxAmount = 0
        row.taxPrice = 0
        row.totalPrice = 0
    } else {
        // 恢复
        const original = row._originalPrice
        row.price = original?.price ?? (row.productInfo?.defaultPrice || 0)
        row.discount = original?.discount ?? 0
        row.tax = original?.tax ?? 13
        row.quantity = original?.quantity ?? 0
        calculateDetailPrice(row)
    }

}


//  选中的商品
const handleSelectedGoods = (selected) => {
    if (selected.length === 0) {
        goodsVisible.value = false
        return
    }

    const newRows = selected.map(item => {
        // 获取默认单位
        let unitList = item.unitList || [];
        let baseUnit = null;
        let unitConversion = 1;

        console.log("selected", selected);
        const row = {
            id: Date.now() + Math.random(),
            productInfo: {
                goodsId: item.id,
                name: item.name,
                goods_code: item.code,
                photo: item.photo || '',
                unitId: item.unit,
                unit: item.unitName,
                unitList: unitList,
                specification: item.specification,
                brand: item.brandName,
                defaultPrice: item.price || item.defaultPrice || 0,
                warehouseName: item.warehouseName,
            },
            useCount: item.stock,
            goodsId: item.id,
            goods_code: item.code,
            warehouse: item.warehouseName,
            gift: false,
            price: item.defaultPrice || 0,
            discount: 0,
            tax: 13,
            quantity: 0,
            discountPrice: 0,
            taxAmount: 0,
            discountAmount: 0,
            salesCost: 0,
            taxPrice: 0,
            totalPrice: 0,
            remarks: '',
            // 多单位相关字段
            unitList: unitList,
            // selectedUnit: selectedUnit?.id || null,
            baseUnit: baseUnit,
            unitConversion: unitConversion,
            baseQuantity: 0
        };

        calculateDetailPrice(row);
        return row;
    });

    // 替换当前行
    if (currentIndex.value !== null && orderDetails.value[currentIndex.value]) {
        orderDetails.value.splice(currentIndex.value, 1, ...newRows)
    } else {
        orderDetails.value.push(...newRows)
    }

    // 关闭弹窗
    goodsVisible.value = false

}


// 源单
const quotationSelectVisible = ref(false)

// 源单选择
const openSourceOrderDialog = () => {
    if (!salesOrderForm.customerCode) {
        ElMessage.warning('请先选择客户')
        return
    }
    quotationSelectVisible.value = true
}

//源单回显
const handleSelectQuotation = async (selectedQuotation) => {
    console.log('选中的报价单:', selectedQuotation)


    const res = await axios.get('/api/sales/selectQuotation', {
        params: { id: selectedQuotation.id }
    })

    if (res.data.code != 200) {
        ElMessage.error('加载报价单明细失败: ' + (res.data.msg || ''))
        return
    }

    const quotation = res.data.quotation
    salesOrderForm.quotationCode = quotation.code || ''
    salesOrderForm.quotationId = quotation.id || ''
    const details = res.data.quotationDetList || []
    if (details.length == 0) {
        ElMessage.warning('该报价单无商品明细')
        return
    }


    orderDetails.value = []

    const mappedRows = details.map(item => ({
        id: Date.now() + Math.random(),
        goods_code: item.goods_code || '',
        productInfo: item.goodsId ? {
            goodsId: item.goodsId,
            name: item.name,
            goods_code: item.goods_code,
            moreUnit: item.moreUnit || '',
            utilId: null,
            unit: item.unit || '',
            specification: item.specification || '',
            brand: item.brand || '',
            defaultPrice: item.price || 0
        } : null,
        goodsId: item.goodsId || '',
        warehouse: item.warehouse || '',
        useCount: item.useCount || 0,
        price: item.price || 0,
        discount: item.discount || 0,
        discountPrice: item.discountPrice || 0,
        tax: item.tax || 13,
        salesCost: item.salesCost || 0,
        discountAmount: item.discountAmount || 0,
        taxAmount: item.taxAmount || 0,
        taxPrice: item.taxPrice || 0,
        quantity: item.quantity || 1,
        totalPrice: item.totalPrice || 0,
        remarks: item.remarks || '',
        gift: item.gift == 1,
        baseQuantity: item.baseQuantity || 0,
    }))
    orderDetails.value = mappedRows
    assignUnitList();
    quotationSelectVisible.value = false
    ElMessage.success('已成功加载报价单商品明细')
}

// 格式化价格：保留两位小数
const formatPrice = (num) => Math.round(num * 100) / 100

// 计算优惠后金额
const calculateTaxEndCost = () => {
    const total = orderDetails.value.reduce((sum, row) => sum + (row.totalPrice || 0), 0)
    salesOrderForm.taxEndCost = formatPrice(total - (salesOrderForm.taxCost || 0))
}
// 计算单行价格
const calculateDetailPrice = (row) => {
    if (row.gift) {
        row.salesCost = 0
        row.discountAmount = 0
        row.discountPrice = 0
        row.taxPrice = 0
        row.totalPrice = 0
        row.taxAmount = 0
    } else {
        if (!row.productInfo || !row.price || !row.quantity || row.quantity < 1) {
            row.discountPrice = 0
            row.taxPrice = 0
            row.totalPrice = 0
            row.taxAmount = 0
            row.salesCost = 0
            row.discountAmount = 0
        } else {
            row.discountPrice = formatPrice(row.price * (1 - (row.discount || 0) / 100))
            row.taxPrice = formatPrice(row.discountPrice * (1 + (row.tax || 0) / 100))
            row.totalPrice = formatPrice(row.taxPrice * row.quantity)
            row.taxAmount = formatPrice((row.taxPrice - row.discountPrice) * row.quantity)
            row.discountAmount = formatPrice((row.price - row.discountPrice) * row.quantity)
            row.salesCost = formatPrice(row.discountPrice * row.quantity)
        }
    }
    calculateTaxEndCost()
}



const getSummaries = ({ columns, data }) => {
    const sums = []
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = '合计'
            return
        }
        if (column.property === 'baseQuantity') {
            sums[index] = data.reduce((sum, row) => sum + (row.baseQuantity || 0), 0)
            return
        }
        if (column.property === 'totalPrice') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.totalPrice || 0), 0))

            return
        }
        if (column.property === 'taxAmount') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.taxAmount || 0), 0))
            return
        }
        if (column.property === 'salesCost') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.salesCost || 0), 0))
            return
        }

        if (column.property === 'discountAmount') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.discountAmount || 0), 0))
            return
        }
        sums[index] = ''
    })
    return sums
}

// 验证订购数量
const validateQuantity = (row) => {
    if (row.baseQuantity > row.useCount && row.useCount >= 0) {
        ElMessage.warning(`订购数量不能大于可用库存数量 ${row.useCount}`)
        row.baseQuantity = 0;
        row.quantity = 0;
        calculateDetailPrice(row)
    }
}
// 添加行
const addRow = (index) => {
    orderDetails.value.splice(index + 1, 0, {
        id: Date.now() + Math.random().toString(36).slice(2, 8),
        goodsId: '',
        code: '',
        productInfo: {},
        warehouse: '',
        useCount: 0,
        price: 0,
        discount: 0,
        discountPrice: 0,
        tax: 13,
        salesCost: 0,
        discountAmount: 0,
        taxAmount: 0,
        taxPrice: 0,
        quantity: 0,
        totalPrice: 0,
        remarks: '',
        gift: false,
        unitList: [],
        selectedUnit: null,
        baseUnit: null,
        baseQuantity: 0,
        unitConversion: 1
    })
}

// 删除行
const deleteRow = (row) => {
    if (orderDetails.value.length <= 1) {
        ElMessage.warning('至少保留一条商品明细')
        return
    }
    const index = orderDetails.value.indexOf(row)
    orderDetails.value.splice(index, 1)

}

// 打开客户选择弹窗
const openCustomerDialog = () => {
    customerDialogVisible.value = true
}

// 客户选择
const handleSelectCustomer = (customers) => {
    console.log('已选择客户:', customers)
    if (customers && customers.length > 0) {
        const customer = customers[0]
        salesOrderForm.customerId = customer.id
        salesOrderForm.customerCode = customer.code
        salesOrderForm.customerAddress = customer.primaryContactAddress || ''
        salesOrderForm.customerName = customer.name
        salesOrderForm.customerType = customer.typeName

    }
    console.log('选择客户后表单数据:', salesOrderForm)
    customerDialogVisible.value = false
}

// 日期格式化
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 保存
const save = async () => {
    console.log('保存时的状态:', { isEdit: isEdit.value, code: code.value })

    if (isViewOnly.value) {
        ElMessage.warning('当前为查看模式，无法保存修改')
        return false
    }



    if (!salesOrderForm.customerCode) {
        ElMessage.error('请选择客户')
        return false
    }

    const validDetails = orderDetails.value.filter(detail => detail.productInfo);
    if (validDetails.length === 0) {
        ElMessage.error('请至少选择一个商品进行保存')
        return false
    }

    const hasInsufficientStock = validDetails.some(detail =>
        detail.baseQuantity > detail.useCount && detail.useCount >= 0
    )

    if (hasInsufficientStock) {
        ElMessage.error('存在商品库存不足的情况')
        return false
    }

     for (let detail of validDetails) {
        if (!detail.quantity || detail.quantity <= 0 || !Number.isInteger(detail.quantity)) {
            ElMessage.error('订购数量必须为正整数')
            return false
        }
    }

    const getDeliveryValue = (label) => {
        const map = { '快递物流': '1', '自配': '2', '其他': '3' }
        return map[label] || label
    }

    const getPaymentValue = (label) => {
        const map = { '现结': '1', '货到付款': '2', '分期付款': '3', '先款后付': '4', '月结': '5', '不定期付款': '6' }
        return map[label] || label
    }

    // 主表数据
    const salesOrder = {
        code: code.value,
        quotationCode: salesOrderForm.quotationCode,
        quotationId: salesOrderForm.quotationId,
        customerCode: salesOrderForm.customerCode,
        customerType: salesOrderForm.customerType,
        customerName: salesOrderForm.customerName,
        customerId: salesOrderForm.customerId,
        workName: salesOrderForm.workName,
        date: formatDate(salesOrderForm.date),
        productDate: salesOrderForm.productDate ? formatDate(salesOrderForm.productDate) : '',
        customerAddress: salesOrderForm.customerAddress,
        remarks: salesOrderForm.remarks,
        payment: getPaymentValue(salesOrderForm.payment),
        delivery: getDeliveryValue(salesOrderForm.delivery),
        // taxCost: salesOrderForm.taxCost,
        // taxEndCost: salesOrderForm.taxEndCost,

        orderPrice: orderDetails.value.reduce((sum, row) => sum + (row.totalPrice || 0), 0),
        salesAmount: orderDetails.value.reduce((sum, row) => sum + (row.salesCost || 0), 0),
        itemCount: orderDetails.value.reduce((sum, row) => sum + (row.baseQuantity || 0), 0),
        taxAmount: orderDetails.value.reduce((sum, row) => sum + (row.taxAmount || 0), 0),

    }

    // 明细表数据
    const salesOrderDetails = validDetails.map(detail => {
        const p = detail.productInfo || {}
        // 查找选中的单位对象以获取 unitsId 和 name
        console.log("goods-----------:", detail);
        console.log("goods-----------:", p);
        return {
            goodsId: detail.goodsId,
            goods_code: p.code || detail.goods_code || '',
            name: p.name || '',
            warehouse: detail.warehouse,
            price: formatPrice(detail.price),
            discount: formatPrice(detail.discount),
            tax: formatPrice(detail.tax),
            quantity: detail.quantity,
            baseQuantity: detail.baseQuantity,
            gift: detail.gift ? 1 : 0,
            discountPrice: formatPrice(detail.discountPrice),
            taxPrice: formatPrice(detail.taxPrice),
            salesCost: formatPrice(detail.salesCost),
            totalPrice: formatPrice(detail.totalPrice),
            remarks: detail.remarks,
            discountAmount: formatPrice(detail.discountAmount),
            taxAmount: formatPrice(detail.taxAmount),
            unit: p.unit || '',
            specification: p.specification || '',
            brand: p.brand || '',
            moreUnit: p.unitName||p.moreUnit|| p.unit,
        }
    })


    let response
    if (code.value) {
        // 编辑模式
        response = await axios.post('/api/sales/updateSalesOrder', {
            salesOrder: {
                ...salesOrder,
                id: salesOrderForm.id || quotationId.value,
            },
            salesProductList: salesOrderDetails
        })

        if (response.data.code == 200) {

            ElMessage.success('修改成功')
            return true
        } else {
            ElMessage.error('修改失败 : ' + response.data.msg)
            return false
        }
    } else {
        // 新增模式
        response = await axios.post('/api/sales/salesOrderAdd', {
            salesOrder: salesOrder,
            salesProductList: salesOrderDetails
        })

        if (response.data.code == 200) {
            salesOrderForm.id = response.data.id
            code.value = response.data.salesOrderCode
            ElMessage.success('保存成功')
            return true
        } else {
            ElMessage.error('保存失败 : ' + response.data.msg)
            return false
        }
    }
}

// 保存并新增
const saveAndNew = async () => {
    const saveResult = await save()

    if (!saveResult) {
        return
    }
    resetForm()

}

// 审核
const audit = () => {
    isAudited.value = true
    ElMessage.success('审核成功')
}

// 重置表单
const resetForm = () => {
    salesOrderForm.customerName = ''
    salesOrderForm.customerCode = ''
    salesOrderForm.workName = staffName
    salesOrderForm.date = new Date()
    salesOrderForm.productDate = ''
    salesOrderForm.customerAddress = ''
    salesOrderForm.remarks = ''
    salesOrderForm.payment = ''
    salesOrderForm.delivery = ''
    salesOrderForm.taxCost = 0
    salesOrderForm.taxEndCost = 0
    orderDetails.value = [{
        id: Date.now() + Math.random().toString(36).slice(2, 8),
        code: '',
        goodsId: '',
        productInfo: null,
        warehouse: '',
        useCount: 0,
        price: 0,
        discount: 0,
        discountPrice: 0,
        tax: 13,
        salesCost: 0,
        baseQuantity: 0,
        discountAmount: 0,
        taxAmount: 0,
        taxPrice: 0,
        quantity: 0,
        totalPrice: 0,
        remarks: '',
        gift: false
    }]
    isAudited.value = false
    code.value = ''
    isEdit.value = false
}

// 获取销售订单详情
const fetchSalesOrderDetail = async (codeParam) => {
    const from = route.query.from
    if (from === 'edit') {
        isEdit.value = true
        isViewOnly.value = false
    } else if (from === 'view') {
        isViewOnly.value = true
        isEdit.value = false
    }

    console.log('codeParam', codeParam)
    const response = await axios.get('/api/sales/salesOrderByCode', {
        params: { code: codeParam }
    })

    if (response.data.code == 200) {
        console.log('获取到的销售订单详情:', response.data)
        const salesOrder = response.data.salesOrder
        const salesOrderDetails = response.data.salesProductList || []

        // 回显主表数据
        code.value = salesOrder.code || ''
        salesOrderForm.customerCode = salesOrder.customerCode || ''
        salesOrderForm.workName = salesOrder.workName || ''
        salesOrderForm.date = salesOrder.date ? new Date(salesOrder.date) : new Date()
        salesOrderForm.productDate = salesOrder.productDate ? new Date(salesOrder.productDate) : ''
        salesOrderForm.customerAddress = salesOrder.customerAddress || ''
        salesOrderForm.remarks = salesOrder.remarks || ''
        salesOrderForm.payment = paymentMap[salesOrder.payment] || salesOrder.payment || ''
        salesOrderForm.delivery = deliveryMap[salesOrder.delivery] || salesOrder.delivery || ''
        salesOrderForm.customerName = salesOrder.customerName


        salesOrderForm.taxCost = salesOrder.taxCost || 0
        salesOrderForm.taxEndCost = salesOrder.taxEndCost ||
            (salesOrder.salesAmount - (salesOrder.taxCost || 0))


        // 回显明细表数据
        orderDetails.value = salesOrderDetails.map(item => ({
            id: item.id || Date.now(),
            goods_code: item.goods_code || '',
            productInfo: item.goodsId ? {
                goodsId: item.goodsId,
                name: item.name,
                code: item.goods_code,
                moreUnit: item.moreUnit || '',
                utilId: null,
                unit: item.unit || '',
                specification: item.specification || '',
                brand: item.brand || '',
                defaultPrice: item.price || 0
            } : null,
            goodsId: item.goodsId,
            warehouse: item.warehouse || '',
            useCount: item.useCount || 0,
            price: item.price || 0,
            discount: item.discount || 0,
            discountPrice: item.discountPrice || 0,
            tax: item.tax || 13,
            salesCost: item.salesCost || 0,
            discountAmount: item.discountAmount || 0,
            taxAmount: item.taxAmount || 0,
            taxPrice: item.taxPrice || 0,
            quantity: item.quantity || 0,
            totalPrice: item.totalPrice || 0,
            remarks: item.remarks || '',
            gift: item.gift == 1 ? true : false,
            baseQuantity: item.baseQuantity || 0,
        }))
        assignUnitList();
        // 如果是已审核状态，设置为只读
        if (salesOrder.auditStatus === '2') {
            isAudited.value = true
        }
    } else {
        ElMessage.error('获取销售订单详情失败: ' + (response.data.message || response.data.msg || '未知错误'))
    }
}

const assignUnitList = () => {
    const map = FreeGoodsRef.value?.unitOptionsMap;
    if (!map) {
        setTimeout(assignUnitList, 100);
        return;
    }
    console.log(3)
    // 检查是否所有商品的 unitList 都已加载
    const allLoaded = orderDetails.value.every(i => {
        const goodsId = String(i.goodsId).trim();
        return map[goodsId] !== undefined;
    });
    console.log(4)
    if (!allLoaded) {
        setTimeout(assignUnitList, 100);
        return;
    }
    console.log(5)
    // ✅ 开始赋值 unitList 和 unitId
    console.log("map")
    console.log(map)
    console.log(orderDetails.value)
    orderDetails.value.forEach(i => {
        const goodsId = String(i.goodsId).trim();
        const unitList = map[goodsId] || [];
        console.log("unitList:", unitList);
        i.productInfo.unitList = unitList;

        // 如果已经有 unitId（比如后端返回了），就保留        -------------------------从此处后面的视情况赋值，这里unitId为null是从其他单生成入库单时，没有unitId导致的，如果自己的明细中包含unitId，就不用考虑下面的代码
        if (i.productInfo.unitId) {
            return;
        }

        unitList.forEach(j => {
            if (i.productInfo.moreUnit == j.name) {
                i.productInfo.unitId = j.id;
            }
        })


    })
}

const updateStockByWarehouse = async (row) => {
    if (!row.goodsId || !row.warehouse) {
        console.log('缺少必要参数：goodsId 或 warehouse');
        return;
    }

    try {
        const response = await axios.get('/api/sales/getStock', {
            params: {
                goodsId: row.goodsId,
                warehouse: row.warehouse
            }
        });

        if (response.data.code == 200) {
            row.useCount = response.data.useCount || 0;
        } else {
             row.useCount = 0;
        }
    } catch (error) {
        ElMessage.error('查询库存时发生错误');
    }
}
const deliveryMap = {
    '1': '快递物流',
    '2': '自配',
    '3': '其他'
}

const paymentMap = {
    '1': '现结',
    '2': '货到付款',
    '3': '分期付款',
    '4': '先款后付',
    '5': '月结',
    '6': '不定期付款'
}
// 初始化
onMounted(() => {
    const codeParam = route.query.code

    if (codeParam) {
        fetchSalesOrderDetail(codeParam)
    }

})
</script>

<style scoped>
.sales-order-container {
    padding: 20px;
    background-color: white;
    min-height: 85vh;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e7ed;
}

.header h2 {
    font-size: 1.5rem;
    color: #333;
    margin: 0;
}

.header-right {
    display: flex;
    gap: 8px;
}

.top-form {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    align-items: center;
}

.seq-cell {
    position: relative;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.operation-area {
    display: flex;
    gap: 4px;
}

.operation-btn {
    cursor: pointer;
    font-weight: bold;
    width: 18px;
    text-align: center;
}

.operation-btn.add:hover {
    color: green;
}

.operation-btn.delete:hover:not(.disabled) {
    color: red;
}

.product-cell {
    min-height: 30px;
    padding: 8px;
}

.placeholder-text {
    color: #999;
    font-size: 13px;
}

.summary-row {
    font-weight: bold;
    color: #d4380d;
}

/* 赠品列复选框居中 */
.el-table .cell .el-checkbox {
    display: flex;
    justify-content: center;
}
</style>